package com.dyzx.hbb.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomController;
import com.dyzx.hbb.common.utils.DateFormat;
import com.dyzx.hbb.modules.sys.entity.SysUser;
import com.dyzx.hbb.modules.sys.query.UserMiniQuery;
import com.dyzx.hbb.modules.sys.query.UserQuery;
import com.dyzx.hbb.modules.sys.service.SysRoleUserService;
import com.dyzx.hbb.modules.sys.service.SysUserService;
import com.dyzx.hbb.modules.sys.vo.*;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import com.dyzx.hbb.security.model.SysUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 * 负责处理用户的增删改查、密码修改等操作
 */
@RequestMapping("/sys/user")
@RestController
@Tag(name = "02.用户管理", description = "用户相关接口，包括用户信息的增删改查、状态管理等")
public class UserController extends BaseCustomController<SysUserService, SysUser, UserQuery> {

    @Autowired
    private SysUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysRoleUserService sysUserRoleService;


    /**
 * 分页查询用户列表
 */
/*@Operation(summary = "分页查询用户列表", description = "根据查询条件分页获取用户信息，支持账号、名称、状态等条件过滤")
@GetMapping("/list")
public Result<SysUser> list(
        @Parameter(description = "查询条件对象") UserQuery query) {
    return userService.findByPage(query);
}*/

    /**
 * 新增/修改用户
 */
@Operation(summary = "新增/修改用户", description = "新增或修改用户信息，id为空时新增，不为空时修改")
@PostMapping("/edit")
public Result<?> edit(
        @Parameter(description = "用户信息对象") @RequestBody UserVO dto) {
    SysUser user = new SysUser();
    BeanUtil.copyProperties(dto, user);
    boolean flag = false;
    if (dto.getId() == null || dto.getId() == 0) {
        user.setId(null);
        user.setCreateDate(System.currentTimeMillis());
        user.setUpdateDate(System.currentTimeMillis());
        user.setPassword(passwordEncoder.encode("123456"));
        flag = userService.save(user);
    } else {
        user.setUpdateDate(System.currentTimeMillis());
        flag = userService.updateById(user);
    }
    return flag ? Result.ok() : Result.error();
}
    @Override
    protected SysUserService getBaseService() {
        return userService;
    }

    @Override
    protected MyLambdaQueryWrapper<SysUser> queryWrapper(UserQuery query) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysUser> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.organName(SysUser::getOrganId).as("organ_name").select(SysUser::getId,SysUser::getName,SysUser::getType, SysUser::getPosition,  SysUser::getAvatar,SysUser::getCreateDate, SysUser::getUpdateDate, SysUser::getStatus, SysUser::getPhone, SysUser::getAccount);
        wrapper.select("(SELECT GROUP_CONCAT(name SEPARATOR ',')  FROM sys_role where id in(SELECT role_id FROM sys_role_user where user_id=sys_user.id))").as("role");
        wrapper.imageUrl(SysUser::getAvatar).as("avatar_url");
           //     .brokersName(SysUser::getBroker).as("broker_name");
        if (query != null) {

            wrapper.like(StringUtils.isNotBlank(query.getAccount()), SysUser::getAccount, query.getAccount())
                    .inSet(StringUtils.isNotBlank(query.getBroker()), SysUser::getName, query.getBroker())
                    .inSet(query.getStatus() != null, SysUser::getStatus, query.getStatus())
                    .inSet(query.getDeptId() != null, SysUser::getDeptId, query.getDeptId())
                    .inSet(query.getType() != null, SysUser::getType, query.getType())
                    .inSet(query.getPosition() != null, SysUser::getPosition, query.getPosition())
                    .inSet(query.getStatus() != null, SysUser::getStatus, query.getStatus())
                    .dateBetween(StringUtils.isNotBlank(query.getCreateDate()), SysUser::getCreateDate, DateFormat.DATE, query.getCreateDate())
                    .eq(SysUser::getOrganId, query.getOrganId()!=null?query.getOrganId():organId);

            return wrapper;
        } else {
            return wrapper;
        }

    }

    protected MyLambdaQueryWrapper<SysUser> queryWrapperMini(UserMiniQuery query) {
        MyLambdaQueryWrapper<SysUser> wrapper = new MyLambdaQueryWrapper<>();
        //  sysUserLambdaQueryWrapper.imageUrl(SysUser::getAvatar).as("avatar_url");
        wrapper.select(SysUser::getId,  SysUser::getName);
        if (query != null) {
            Long organId = SecurityContextHolder.getOrganId();

            wrapper
                    .inSet(StringUtils.isNotBlank(query.getBroker()), SysUser::getName, query.getBroker())
                    .inSet(query.getType() != null, SysUser::getType, query.getType())
                    .inSet(query.getPosition() != null, SysUser::getPosition, query.getPosition())
                    .eq( SysUser::getOrganId, organId);

            return wrapper;
        } else {
            return wrapper;
        }

    }

    @Override
    protected MyLambdaQueryWrapper<SysUser> queryInfoWrapper() {

        Long organId = SecurityContextHolder.getOrganId();
        //  sysUserLambdaQueryWrapper.select(SysUser::getId, SysUser::getAccount, SysUser::getName);
        MyLambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new MyLambdaQueryWrapper<>();

        sysUserLambdaQueryWrapper.imageUrl(SysUser::getAvatar).as("avatar_url").organName(SysUser::getOrganId).as("organ_name").brokersName(SysUser::getBroker).as("broker_name");
      //  sysUserLambdaQueryWrapper.imageUrl(SysUser::getAvatar).as("avatar_url");
        sysUserLambdaQueryWrapper.deptName(SysUser::getDeptId).as("dept_name").select(SysUser::getId,SysUser::getName,SysUser::getType, SysUser::getPosition, SysUser::getBroker,  SysUser::getAvatar, SysUser::getDeptId, SysUser::getCreateDate, SysUser::getUpdateDate, SysUser::getStatus, SysUser::getPhone,  SysUser::getBroker,SysUser::getAccount);

        sysUserLambdaQueryWrapper.eq( SysUser::getOrganId, organId);

        return sysUserLambdaQueryWrapper;

    }


    /**
     * 删除用户
     */
/*    @PostMapping("/delete")
/*    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @PostMapping("/delete")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户信息")
    public Result<?> delete(@RequestBody long id) {
        userService.byDelete(id);
        return Result.ok();
    }*/


    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@RequestBody UserVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        if(StringUtils.isEmpty(entity.getPassword())){
            return Result.error("密码不能为空");
        }

        SysUser entityCopy = new SysUser();
        BeanUtil.copyProperties(entity, entityCopy);
        if (entity.getBroker() != null) {
            entityCopy.setBroker(entity.getBroker());
        }
        if(StringUtils.isNotEmpty(entity.getPhone())){
            SysUser byPhone = getBaseService().getByPhone(entity.getPhone());
            if (byPhone != null) {
                return Result.error("手机号已存在");
            }
        }

        SysUser byAccount = getBaseService().getByAccount(entity.getAccount());
        if (byAccount != null) {
            return Result.error("用户名已存在");
        }
        Long organId = SecurityContextHolder.getOrganId();
        entityCopy.setOrganId(organId);
        String password1=passwordEncoder.encode(entity.getPassword());
        entityCopy.setPassword(password1);
        boolean save = getBaseService().save(entityCopy);
        if (save) {
            if (StringUtils.isNotEmpty(entity.getRole())) {

                List<Long> roleIds = Arrays.stream(entity.getRole().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Long::valueOf)
                        .collect(Collectors.toList());
                if (!roleIds.isEmpty()) {

                    sysUserRoleService.userByRoles(entityCopy.getId(), roleIds);
                }


            }
           // getBaseService().sendNewPassword(entityCopy.getPhone(), entity.getPassword());
            return Result.ok(true);
        } else {
            return Result.error("保存失败");
        }
    }

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @PutMapping
    public Result<Boolean> update(@RequestBody UserUVO entity) {
        Long organId = SecurityContextHolder.getOrganId();
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        SysUser entityCopy = new SysUser();
        BeanUtil.copyProperties(entity, entityCopy);

        if (entityCopy.getId() == null) {
            return Result.error("id不能为空");
        }
        entityCopy.setOrganId(null);
        if (entity.getBroker() != null) {
            entityCopy.setBroker(StringUtils.join(entity.getBroker(), ","));
        }
        SysUser byId = getBaseService().getById(entityCopy.getId());
        if(!Objects.equals(byId.getOrganId(), organId)){
            return Result.error("用户数据不存在");
        }
        return Result.ok(getBaseService().updateById(entityCopy));
    }
    /**
     * 获取用户
     */
    @Operation(summary = "获取用户")
    @PostMapping("/change")
    public Result<String> change(@RequestBody UserChangeUVO entity) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        SysUser byId = getBaseService().getById(userId);
        if (byId == null) {
            return Result.error("数据不存在");
        }
        switch (entity.getType()) {
            case 1:
                byId.setAvatar(entity.getId());
                break;
            case 2:
                byId.setPassword(passwordEncoder.encode(entity.getData()));
                break;
            case 3:
                byId.setName(entity.getData());
                break;
            case 4:
                byId.setPhone(entity.getData());
                break;

            default:
                return Result.error("类型错误");
        }
        boolean update = getBaseService().updateById(byId);
        if (update) {
            return Result.ok();
        } else {
            return Result.error("更新失败");
        }
    }


    /**
     * 删除
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        Long organId = SecurityContextHolder.getOrganId();
        if (id == null) {
            return Result.error("id不能为空");
        }
        SysUser byId = getBaseService().getById(id);
        if (byId == null) {
            return Result.error("数据不存在");
        }
        if(byId.getType() == 1){
            return Result.error("管理员账号不能删除");
        }
        if(!Objects.equals(byId.getOrganId(), organId)){
            return Result.error("用户数据不存在");
        }
        return Result.ok(getBaseService().removeById(id));
    }

    /**
     * 获取用户简易列表
     */
    @Operation(summary = "获取用户简易列表")
    @GetMapping("/mini_list")
    public Result<List<SysUser>> miniList(UserMiniQuery query) {
        MyLambdaQueryWrapper<SysUser> wrapper = queryWrapperMini(query);
        return Result.ok(getBaseService().list(wrapper));
    }

    /**
     * 更改密码
     */
    @Operation(summary = "更改密码")
    @PutMapping("/reset_pass")
    public Result<Boolean> resetPass(@RequestBody UserPasswordChangeVO vo) {

        if (StringUtils.isBlank(vo.getOldPassword())) {
            return Result.error("原密码不能为空");
        }
        if (StringUtils.isBlank(vo.getNewPassword())) {
            return Result.error("新密码不能为空");
        }
        Long userId = SecurityContextHolder.getUserId();

        // 验证原密码
        SysUser user = getBaseService().getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!passwordEncoder.matches(vo.getOldPassword(), user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(vo.getNewPassword()));
        user.setUpdateDate(System.currentTimeMillis());
        return Result.ok(getBaseService().updateById(user));
    }
    /**
     * 获取用户详细信息
     */
/*    @Operation(summary = "获取用户详细信息")
    @GetMapping("/info/{id}")
    public Result<SysUser> get(@PathVariable Long id) {
        SysUser byId = getBaseService().getById(id);
        return Result.ok(byId);
    }  */

//currentUser
    @Operation(summary = "获取当前用户信息")
    @GetMapping("/current-user")
    public Result<SysUserInfo> UserCurrentInfoR() {
        Long userId = SecurityContextHolder.getUserId();
        SysUserInfo userInfo = getBaseService().getLoginUserInfo(userId);
        return Result.ok(userInfo);
    }


}
